﻿/*
    Copyright 2013 Bob Moss (bobbyjmoss@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace OpenRAMS.Model
{
    public class Bookings : Booking
    {
        private List<Booking> bookingList;
        private List<int> bookingIDs;

        public List<Booking> getBookingList()
        {
            return bookingList;
        }

        //overloaded database-related variables
        private SqlConnection dbConnection;
        private SqlDataReader dbReader;
        private SqlCommand dbCommand;
        private String dbInString;

        public Bookings()
        {
            //db-related initialisations
            initHardCodedVals();
            try { dbInString = ConfigurationManager.ConnectionStrings["default"].ConnectionString; }
            catch (Exception e) { throw e; }  //this will cause error conditions later

            //initialise lists
            bookingList = new List<Booking>();
            bookingIDs = new List<int>();
        }

        public int Populate()
        {
            return Populate(attribNames[9], "1");   //Loads all bookings marked as 'active'
            //(to query strings, use "'string'". For multiple criteria append " AND field2='criteria'" to criteria parameter)
        }

        public int Populate(String fieldName, String criteria)
        {
            //re-initialise lists
            bookingList = new List<Booking>();
            bookingIDs = new List<int>();

            //Build query - only need a list of IDs to know which bookings to populate list with
            String queryFull = "SELECT " + attribNames[0] + " FROM " + tableName + " ";
            String queryCondition = "WHERE ";

            //verify fieldname is valid - if it isn't, assume criteria is a special case.
            Boolean fieldTest = false;
            for (int i = 0; i <= numAttribs; i++)
            {
                if (attribNames[i] == fieldName)
                {
                    fieldTest = true;
                    break;
                }
            }
            if (!fieldTest) { queryCondition += criteria; }
            else
            {
                queryCondition += fieldName + "=" + criteria;
            }
            queryFull += queryCondition;

            //attempt DB connection
            try
            {
                dbConnection = new SqlConnection(dbInString);
                dbConnection.Open();
            }
            catch { return -1; }

            //create command that will run query
            dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = queryFull;
            dbCommand.CommandType = CommandType.Text;
            dbCommand.CommandTimeout = 15;

            //Run command, and tidy-up if exceptions occur
            try { dbReader = dbCommand.ExecuteReader(); }
            catch
            {
                dbReader.Close();
                dbConnection.Close();
                return -1;
            }

            //read in all the results and add them to list of booking IDs
            while (dbReader.Read())
            {
                try
                {
                    bookingIDs.Add(Convert.ToInt32(dbReader[attribNames[0]].ToString()));
                }
                catch { return -1; }
            }

            //verify at least one result was returned, else error
            if (bookingIDs.Count() < 1) { return -1; }

            //Load found bookings into list
            foreach (int id in bookingIDs)
            {
                Booking newBooking = new Booking();
                int loadNewBooking = newBooking.Load(id);
                if (loadNewBooking < 0) { return -1; }
                else
                {
                    bookingList.Add(newBooking);
                }
            }

            //verify that more than one booking has been added
            if (bookingList.Count() < 1) { return -1; }

            //Clean-up DB connection
            try
            {
                dbReader.Close();
                dbConnection.Close();
            }
            catch { return -1; }
            return 0;
        }
    }
}